from django_redis import get_redis_connection
from rest_framework import serializers


class ImagecodeCheckSerializer(serializers.Serializer):
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(min_length=4,max_length=4)


    def validate(self, attrs):
        image_code_id = attrs["image_code_id"]
        text = attrs["text"]

        redis_conn = get_redis_connection("verify_codes")
        real_image_code_id = redis_conn.get("img_%s" % image_code_id)

        if not real_image_code_id:
            raise serializers.ValidationError("图片验证码错误")

        redis_conn.delete("img_%s" % image_code_id)


        # TODO 从redis中取出的值为字节型,所以要进行解码操作
        real_image_code_id = real_image_code_id.decode()
        if real_image_code_id.lower() != text.lower():
            raise serializers.ValidationError("验证码输入错误")


        # 判断是否图片验证码是否是在60秒内验证的
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            raise serializers.ValidationError("请求次数过于频繁")

        return attrs

